import base64
import hashlib
import hmac
import urllib.parse
from datetime import datetime

def generate_auth_url(host_url, api_key, api_secret):
    # 获取当前时间，并格式化为 RFC1123 日期格式
    date = datetime.utcnow().strftime('%a, %d %b %Y %H:%M:%S GMT')
    # 解析主机
    url_parts = urllib.parse.urlparse(host_url)
    host = url_parts.netloc
    # 拼接签名原始字符串
    signature_origin = f"host: {host}\ndate: {date}\nGET {url_parts.path} HTTP/1.1"
    # 使用 HMAC-SHA256 生成签名摘要
    signature_sha = hmac.new(api_secret.encode('utf-8'), signature_origin.encode('utf-8'), hashlib.sha256).digest()
    # 对摘要进行 Base64 编码
    signature = base64.b64encode(signature_sha).decode('utf-8')
    # 构建 authorization 参数（Base64 编码前）
    authorization_origin = f'api_key="{api_key}", algorithm="hmac-sha256", headers="host date request-line", signature="{signature}"'
    # 对 authorization 参数进行 Base64 编码
    authorization = base64.b64encode(authorization_origin.encode('utf-8')).decode('utf-8')
    # 构建完整的鉴权 URL
    query_params = {
        'authorization': authorization,
        'date': date,
        'host': host
    }
    query_string = urllib.parse.urlencode(query_params)
    auth_url = f"{host_url}?{query_string}"

    return auth_url